﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;


class BundleInfo
{
    AssetBundle _bundle = null;
    Dictionary<string, Object> _assetDict = new Dictionary<string, Object>();

    public BundleInfo(AssetBundle bundle)
    {
        _bundle = bundle;
    }

    public Object GetAsset(string assetName)
    {
        Object o;
        if (!_assetDict.TryGetValue(assetName, out o))
        {
            o = _bundle.LoadAsset(assetName);
            if (o)
                _assetDict[assetName] = o;
        }
        return o;
    }
}

public class CharacterABMgr
{
    static string bundleURL
    {
        get
        {
            return Application.dataPath+ "/Assetbundles";
        }
    }

    Dictionary<string, BundleInfo> _bundleDict = new Dictionary<string, BundleInfo>();

    BundleInfo GetAssetBundle(string bundleName)
    {
        BundleInfo bi;
        if (!_bundleDict.TryGetValue(bundleName, out bi))
        {
            var path = string.Format("{0}/{1}", bundleURL, bundleName);
            var ab = AssetBundle.LoadFromFile(path);
            if (ab)
            {
                bi = new BundleInfo(ab);
                _bundleDict[bundleName] = bi;
            }
        }
        return bi;
    }

    // 为了简单起见，同步加载资源
    public T LoadAsset<T>(string bundleName, string assetName) where T : Object
    {
        var bi = GetAssetBundle(bundleName);
        if (bi == null)
            throw new Exception(string.Format("no bundle name:{0}", bundleName));
        var o = bi.GetAsset(assetName);
        if (o == null)
            throw new Exception(string.Format("no asset:{0} in bundle:{1}", assetName, bundleName));
        return o as T;
    }
}
